package com.test.mywebtest.util;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class DCSUtils {

    /**
     * POST请求发送MultipartFile文件参数
     */
    public static String doPostFile(String url, MultipartFile file, String fileParName,Map<String, String> param) {
        String resultMap = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        String fullurl = "";

        //请求参数
        for (String key : param.keySet()) {
            list.add(new BasicNameValuePair(key, param.get(key)));
        }
        try {
            fullurl = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        } catch (Exception e) {
            result = "下载失败";
            e.printStackTrace();
        }

        try {
            HttpPost httpPost = new HttpPost(url + "?" + fullurl);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);


            byte[] bytes = file.getBytes();
            builder.addBinaryBody("file", bytes, ContentType.MULTIPART_FORM_DATA, UUID.randomUUID().toString());// 文件流
            //决中文乱码
            // ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            org.apache.http.HttpResponse response = httpClient.execute(httpPost);// 执行提交

            // 设置连接超时时间
            //RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
            //        .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            //httpPost.setConfig(requestConfig);

            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
                resultMap = result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }




    /**
     * 网络文件 转换服务接口
     *
     * @param serverurl 网络文件地址
     * @param param     转换所需参数
     * @return
     */
    public static String sendPost(String serverurl, Map<String, String> param) {
        String result = "";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        String fullurl = "";
        //请求参数
        for (String key : param.keySet()) {
            list.add(new BasicNameValuePair(key, param.get(key)));
        }
        try {
            fullurl = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        } catch (Exception e) {
            result = "下载失败";
            e.printStackTrace();
        }
        HttpPost httpget = new HttpPost(serverurl + "?" + fullurl);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
            } else {
                result = "下载失败";
            }
        } catch (Exception e) {
            result = "下载失败";
            e.printStackTrace();
        } finally {
            httpget.releaseConnection();
        }
        return result;
    }

    /**
     * 网络文件转换为byte二进制
     * @Title: toByteArray
     * @Description:
     * @param @param url
     * @param @return
     * @param @throws IOException    设定文件
     * @return byte[]    返回类型
     * @throws
     */
    public static byte[] toByteArray(String urlStr) throws IOException {
        DataInputStream in = null;
        try{
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            in = new DataInputStream(conn.getInputStream());
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024*4];
            int n=0;
            while ( (n=in.read(buffer)) !=-1) {
                out.write(buffer,0,n);
            }
            return out.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            in.close();
        }

    }
}
